package com.example.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.bean.User;
import com.example.admin.exception.UserTooManyException;
import com.example.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;

@Controller
public class TableController {

    @Autowired
    UserService userService;

    @GetMapping("/basic_table")
    public String basicTable(@RequestParam("a") int a) {
        int b = a / 0;
        return "table/basic_table";
    }

    @GetMapping("user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn", defaultValue = "1") Integer pn,
                             RedirectAttributes ra){

        userService.removeById(id);
        ra.addAttribute("pn", pn);
        return "redirect:/dynamic_table";
    }

    @GetMapping("/dynamic_table")
    public String dynamicTable(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn) {
//        表格内容遍历
//        List<User> users = Arrays.asList(new User("zhangsan", "123456"),
//                new User("lisa", "12344"),
//                new User("haha", "123477"),
//                new User("hehe", "asdfasdf"));
//        model.addAttribute("users", users);
//
//        if (users.size() > 3) {
//            throw new UserTooManyException("用户太多");
//        }
//        从数据库中查出用户
//        List<User> list = userService.list();
//        model.addAttribute("users", list);

//        分页数据查询
        Page<User> userPage = new Page<>(pn, 2);
        Page<User> page = userService.page(userPage, null);
        model.addAttribute("page", page);

        return "table/dynamic_table";
    }

    @GetMapping("/responsive_table")
    public String responsiveTable() {
        return "table/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editableTable() {
        return "table/editable_table";
    }
}
